package com.rockcent.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.helper.TreeHelper;
import com.rockcent.mall.lib.domain.AuthResource;
import com.rockcent.mall.lib.domain.AuthUserResource;
import com.rockcent.mall.lib.domain.UserInfo;
import com.rockcent.mall.lib.domain.enumclass.SystemType;
import com.rockcent.mall.lib.dto.MenuTreeDTO;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.AuthUserHelper;
import com.rockcent.mall.lib.repository.AuthResourceRepository;
import com.rockcent.service.AuthUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by hone on 17-4-5.
 */
public abstract class BaseAuthUserServiceImpl implements AuthUserService {

    private final Logger log = LoggerFactory.getLogger(BaseAuthUserServiceImpl.class);

    @Autowired
    private AuthUserHelper userHelper;

    @Autowired
    private AuthResourceRepository authResourceRepository;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private TreeHelper treeHelper;

    @Autowired
    private ObjectMapper objectMapper;

    public UserInfoDto login(UserInfo userInfo, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.setSession(userInfo, request);
        if(userInfoDto!=null) {
            userInfoDto.permissionList = userHelper.getPermissionList(userInfoDto);

            List<String> setCookieCustomerDomainList = new ArrayList<>();
            userInfoDto.mallMap.forEach((hostname, mallDto) -> {
                String tempDomain = RequestUtils.getFirstDomain(hostname);
                if (StringUtils.isNotEmpty(tempDomain)) {
                    if (!setCookieCustomerDomainList.contains(tempDomain) && !tempDomain.contains("rockcent.com")) {
                        setCookieCustomerDomainList.add(tempDomain);
                    }
                }
            });
            userInfoDto.setCookieCustomerDomainList = setCookieCustomerDomainList;
            userInfoDto.mallMap = null;
            userInfoDto.merchantMap = null;
            userInfoDto.permissionMap = null;
        }
        return userInfoDto;
    }

    /**
     * 获取权限菜单列表
     * @param authUserResources
     * @param userId
     * @return
     */
    public List<MenuTreeDTO> getMenuTreeDTOs(List<AuthUserResource> authUserResources,Long userId,SystemType systemType, boolean setTag, String userToken) {
        List<MenuTreeDTO> menuTreeDTOs = new ArrayList<>();
        if (authUserResources != null && authUserResources.size() > 0) {
            Long userTokenTimer = 30 * 24 * 60 * 60L; // 30天 生命周期
            String type = systemType.toString();
            for (AuthUserResource authUserResource : authUserResources) {
                AuthResource authResource = authResourceRepository.findOne(authUserResource.getResourceId());
                if(authResource==null) {
                    continue;
                }
                if(setTag) {
                    //支持多个链接
                    if (StringUtils.isNotEmpty(authResource.getBackendUrl())) {
                        List<String> urlList = null;
                        try {
                            urlList = objectMapper.readValue(authResource.getBackendUrl(), new TypeReference<List<String>>() {
                            });
                        } catch (Exception e) {
                            log.error("======================>authResource backendUrl error",e);
                        }
                        if (urlList != null && urlList.size() > 0) {
                            for (String str : urlList) {
                                String key = "";
                                if (systemType.equals(SystemType.ADMIN)) {
                                    key = userId + "-";
                                }
                                if (systemType.equals(SystemType.MALL)) {
                                    key = userToken + "-" + authUserResource.getMallId() + "-";
                                }
                                if(systemType.equals(SystemType.MERCHANT)) {
                                    key = userToken + "-" + authUserResource.getMallId() + "-" + authUserResource.getMerchantId() + "-";
                                }
                                redisTemplate.boundValueOps(key + str).set(str);
                                redisTemplate.expire(key + str, userTokenTimer, TimeUnit.SECONDS);
                            }
                        }
                    }
                }
                MenuTreeDTO menuTreeDTO = new MenuTreeDTO();
                menuTreeDTO.setId(authUserResource.getResourceId());
                menuTreeDTO.setLink(authResource.getFrontendUrl());
                menuTreeDTO.setName(authResource.getName());
                menuTreeDTO.setSort(authResource.getSort());
                menuTreeDTO.setParentId(authResource.getParentId()==null?0L:authResource.getParentId());
                menuTreeDTOs.add(menuTreeDTO);
            }
        }
        if(menuTreeDTOs!=null && menuTreeDTOs.size()>0) {
            List<MenuTreeDTO> trees = treeHelper.getChildTreeObjects(menuTreeDTOs, 0L);
            menuTreeDTOs.clear();
            menuTreeDTOs.addAll(trees);
        }
        return menuTreeDTOs;
    }

    /**
     * 获取权限M或B全部菜单列表
     * @param systemType
     * @return
     */
    public List<MenuTreeDTO> getAllMenuTrees(SystemType systemType) {
        List<MenuTreeDTO> menuTreeDTOs = new ArrayList<>();
        if(systemType!=null) {
            List<AuthResource> authResourceList = authResourceRepository.findBySystemType(systemType);
            if (authResourceList != null && authResourceList.size() > 0) {
                for (AuthResource authResource : authResourceList) {
                    MenuTreeDTO menuTreeDTO = new MenuTreeDTO();
                    menuTreeDTO.setId(authResource.getId());
                    menuTreeDTO.setLink(authResource.getFrontendUrl());
                    menuTreeDTO.setName(authResource.getName());
                    menuTreeDTO.setSort(authResource.getSort());
                    menuTreeDTO.setParentId(authResource.getParentId() == null ? 0L : authResource.getParentId());
                    menuTreeDTOs.add(menuTreeDTO);
                }
            }
            if (menuTreeDTOs != null && menuTreeDTOs.size() > 0) {
                List<MenuTreeDTO> trees = treeHelper.getChildTreeObjects(menuTreeDTOs, 0L);
                menuTreeDTOs.clear();
                menuTreeDTOs.addAll(trees);
            }
        }
        return menuTreeDTOs;
    }
}
